package com.my.socket.nio.v30;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by ZhongGang
 * at 2018/8/21 10:39
 */
public class Acceptor implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Acceptor.class);

    private Selector[] selectors = new Selector[3];
    private AtomicInteger index = new AtomicInteger(1);
    private ServerSocketChannel serverSocketChannel;

    Acceptor(ServerSocketChannel serverSocketChannel) throws Exception {
        for (int i = 0; i < this.selectors.length; i++) {
            Selector selector = Selector.open();
            this.selectors[i] = selector;

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!Thread.interrupted()) {
                        try {
                            if (selector.select(10) > 0) {
                                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                                while (iterator.hasNext()) {
                                    SelectionKey selectionKey = iterator.next();
                                    iterator.remove();

                                    Runnable runnable = (Runnable) selectionKey.attachment();
                                    LOGGER.info("attachment: {}, selection key: {}", runnable, selectionKey);
                                    runnable.run();
                                }
                            }
                        } catch (Exception e) {
                            LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
                        }
                    }
                }
            }).start();
        }

        this.serverSocketChannel = serverSocketChannel;
    }

    @Override
    public void run() {
        try {
            SocketChannel socketChannel = this.serverSocketChannel.accept();
            if (socketChannel != null) {
                LOGGER.info("incoming socket: {}", socketChannel);

                Selector selector = this.selectors[this.index.getAndIncrement() % this.selectors.length];
                Reader reader = new Reader(selector, socketChannel);
                SelectionKey selectionKey = socketChannel.register(selector, SelectionKey.OP_READ, reader);
                LOGGER.info("register read event, selection key: {}", selectionKey);
            }
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
        }
    }
}
